package com.xunlai.infra.permission.manager.authority.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xunlai.infra.permission.common.exception.ExceptionCodeEnum;
import com.xunlai.infra.permission.manager.web.vo.BaseResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 返回response body
 */
@Slf4j
public abstract class AbstractResponseBodyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    public static final int SUCCESS = ExceptionCodeEnum.SUCCESS.getCode();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        exception = handleFailureInternal(request,exception);
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        BaseResponse<Object> fail = BaseResponse.error(failureStatus(request, exception),failureMsg(request,exception));
//        fail.setData(failureBody(request, exception));
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(fail));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    protected abstract AuthenticationException handleFailureInternal(HttpServletRequest request,AuthenticationException exception);

    protected int failureStatus(HttpServletRequest request, AuthenticationException exception) {
        return ExceptionCodeEnum.ACCOUNT_NOT_FOUND.getCode();
    }

    protected Object failureBody(HttpServletRequest request, AuthenticationException exception){
        return null;
    }

    protected String failureMsg(HttpServletRequest request, AuthenticationException exception) {
        return ExceptionCodeEnum.ACCOUNT_NOT_FOUND.getDesc();
    }
}
